package edu.nf.project.webs.accountsAndPermissions;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.nf.project.entitys.entity.accountsAndPermissions.convention.Users;
import edu.nf.project.services.exception.derivedAnomalies.UsersException;
import edu.nf.project.services.accountsAndPermissions.UsersService;
import edu.nf.project.services.response.BaseController;
import edu.nf.project.services.response.ResultVO;
import edu.nf.project.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 账户管理控制器
 */
@RestController
@RequestMapping(value = "/api/users")
public class UsersController extends BaseController {
    /**
     * Users服务层实例
     */
    @Autowired
    private UsersService userService;

    /**
     * 登录
     * @param phone 电话号
     * @param pwd 密码
     * @return 响应对象
     */
    @PostMapping("/login")
    public ResultVO<String> login(@RequestParam("phone") String phone,
                                 @RequestParam("pwd") String pwd) {
        try {
            // 执行登录验证
            Users user = userService.login(phone, pwd);
            // 若用户存在，则打包用户信息为响应对象并返回
            if (user != null) {
                String key = TokenUtils.create(user.getUId());
                return success(key);
            }
            // 否则报错
            throw new UsersException(10001, "账号或密码错误");
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    /**
     * 注册
     * @param user 用户信息
     * @return 响应对象
     */
    @PostMapping("/register")
    public ResultVO<Boolean> register(@RequestBody Users user) {
        try {
            // 执行注册方法
            boolean result = userService.register(user);
            // 若为true则返回true信息
            if (result) {
                return success(true);
            }
            // 否则报错
            throw new UsersException(10002, "手机号已存在");
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    /**
     * 获取用户信息
     * @param userId 用户ID
     * @return 响应对象
     */
    @GetMapping("/{userId}")
    public ResultVO<Users> getUserInfo(@PathVariable Integer userId) {
        try {
            // 执行按ID用户信息方法
            Users user = userService.getUserInfo(userId);
            // 若查到用户则返回用户信息
            if (user != null) {
                return success(user);
            }
            // 否则报错
            throw new UsersException(10003, "用户不存在");
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    /**
     * 更新用户信息
     * @param userId 用户ID
     * @param user 用户信息
     * @return 响应对象
     */
    @PutMapping("/{userId}")
    public ResultVO<Boolean> updateUser(@PathVariable Integer userId,
                                      @RequestBody Users user) {
        try {
            // 设置用户ID
            user.setUId(userId);
            // 执行按ID用户信息方法
            boolean result = userService.updateUser(user);
            // 若为true则返回true
            if (result) {
                return success(true);
            }
            // 否则报错
            throw new UsersException(10004, "手机号已存在");
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    /**
     * 分页查询用户列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param uName 昵称（可选）
     * @param phone 手机号（可选）
     * @return 响应对象
     */
    @GetMapping
    public ResultVO<Page<Users>> getUserList(@RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize,
                                           @RequestParam(required = false) String uName,
                                           @RequestParam(required = false) String phone) {
        try {
            // 创建分页对象，并填入页码与每页数量
            Page<Users> page = new Page<>(pageNum, pageSize);
            // 执行分页方法
            Page<Users> result = userService.getUserList(page, uName, phone);
            // 返回分页结果
            return success(result);
        } catch (Exception e) {
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    /**
     * 获取全部用户信息
     * @return 响应对象
     */
    @GetMapping("/all")
    public ResultVO<List<Users>> getAllUsers() {
        try {
            // 执行按ID用户信息方法
            List<Users> user = userService.getAllUsers();
            return success(user);
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    /**
     * 根据时间区间和用户名查询用户列表
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @param uName 用户名（可选）
     * @return 用户列表
     */
    @GetMapping("/time-range")
    public ResultVO<List<Users>> getUsersByTimeRange(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
            @RequestParam(required = false) String uName) {
        try {
            System.out.println("接收" + startTime);
            System.out.println(endTime);
            System.out.println(uName);
            List<Users> users = userService.getUsersByTimeRange(startTime, endTime, uName);
            return success(users);
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    /**
     * 批量注销用户
     * @param userIds 待注销用户ID数组
     * @return 是否成功
     */
    @DeleteMapping
    public ResultVO<Boolean> deleteUsers(@RequestBody Integer[] userIds) {
        try {
            boolean result = userService.delUsers(userIds);
            if (result) {
                return success(true);
            } else {
                // 可以根据业务需求返回更详细的错误信息，例如部分用户注销失败
                throw new UsersException(10006, "批量注销用户失败");
            }
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }

    @PostMapping("roleCheck")
    public ResultVO<Boolean> isCustomer(@RequestBody Integer userId) {
        try {
            boolean result = userService.isCustomer(userId);
            return success(result);
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, e.getMessage());
        }
    }

    @GetMapping("/verify/{uId}")
    public ResultVO<Boolean> verifyPassword(@PathVariable String uId,
                                            @RequestParam("pwd") String pwd){
        try {
            userService.verifyPassword(uId, pwd);
            return success(true);
        } catch (Exception e) {
            if (e instanceof UsersException) {
                throw e;
            }
            throw new UsersException(10000, "系统错误，请稍后重试");
        }
    }
}
